const express = require("express");
const router = express.Router();
const transformService = require("../service/transformService");
const filesService = require("../service/filesService");
const multer = require('multer')
const path = require('path');
const fs = require('fs');
const fsExtraPromise = require('fs-extra-promise');
const CommonUtil = require("../utils/CommonUtil");

const { ip, port } = require('../config/Config');
const { dir } = require("console");

const jsonWrite = function (res, ret) {
    if (typeof ret === 'undefined') {
        res.json({
            code: '1',
            message: '操作失败'
        });
    } else {
        res.json({
            code: '0',
            message: '操作成功',
            data: ret
        });
    }
};


/**
 * 火星坐标系转GPS坐标
 */
router.get('/GCJ02ToWGS84', function (req, res, next) {
    var lon = req.query.lon,
        lat = req.query.lat;
    const coord = transformService.gcj02towgs84(lon, lat, res);
    jsonWrite(res, coord);
});

/**
 * GPS坐标转火星坐标系
 */
router.get('/WGS84ToGCJ02', function (req, res, next) {
    var lon = req.query.lon,
        lat = req.query.lat;
    transformService.gcj02towgs84(lon, lat, res);
});

/**
 * 百度坐标系转火星坐标系
 */
router.get('/BD09ToGCJ02', function (req, res, next) {
    var lon = req.query.lon,
        lat = req.query.lat;
    transformService.bd09togcj02(lon, lat, res);
});

/**
 * 火星坐标系转百度坐标系
 */
router.get('/GCJ02ToBD09', function (req, res, next) {
    var lon = req.query.lon,
        lat = req.query.lat;
    transformService.gcj02towgs84(lon, lat, res);
});

/**
 * GPS坐标系或者天地图坐标系转百度坐标系
 */
router.get('/WGS84ToBD09', function (req, res, next) {
    var lon = req.query.lon,
        lat = req.query.lat;
    transformService.gcj02towgs84(lon, lat, res);
});

/**
 * 百度坐标系转GPS坐标系或者天地图坐标系
 */
router.get('/BD09ToWGS84', function (req, res, next) {
    var lon = req.query.lon,
        lat = req.query.lat;
    transformService.gcj02towgs84(lon, lat, res);
});


router.get('/proj4Transform', function (req, res, next) {
    var fromWkid = req.query.fromWkid,
        toWkid = req.query.toWkid || 3857,
        coordinate = req.query.coordinate && req.query.coordinate.indexOf(",") > -1 ?
            req.query.coordinate.split(",") : [0, 0];
    const transCoord = transformService.proj4Transform(fromWkid, toWkid, coordinate, res);
    return res.json({
        code: 200,
        message: '转换完成',
        data: {
            coordinate: transCoord
        }
    });
});

/**
 * 文件夹数据坐标转换
 */
router.get('/transformByDir', function (req, res, next) {
    const filesPath = req.query.filesPath;
    const outpath = req.query.outpath;
    if (!filesPath) return;
    // 复制文件夹
    fsExtraPromise.copySync(filesPath, outpath);
    filesService.readGeoJSONFilesInDir({
        dir: outpath, 
        projObj: {
            method: req.query.method || 'gcj02towgs84',
            fromWkid: req.query.iSrid,
            toWkid: req.query.oSrid,
        },
    }, (success, outputDirPath, err)=>{
        success && res.json({
            code: 200,
            message: '转换结束',
            data: {
                outputDirPath
            }
        });
        err && res.json({
            code: 10200,
            message: err,
            data: null
        });
    })
});

//文件路径
const file_server_url = "../uploads";
const upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            var dirpath = path.join(__dirname, file_server_url);
            if (!fs.existsSync(dirpath)) {
                fs.mkdirSync(dirpath);
            }
            cb(null, dirpath)
        },
        filename: function (req, file, cb) {
            const { fieldname, originalname, encoding, mimetype } = file
            // const after = originalname.split('.')[1] ? '.' + originalname.split('.')[1] : '.jpg'
            cb(null, originalname);
        }
    })
})
router.post('/transformByZipGeoData', upload.single('file'), function (req, res, next) {
    try {
        const body = req.body;
        const filePath = req.file?.path;
        const fileName = req.file?.filename;
        //项目根目录
        // process.cwd()
        const outputPath = path.join(__dirname, file_server_url, `${fileName.substring(0, fileName.lastIndexOf("."))}/`);
        CommonUtil.unzip(filePath, outputPath, (destFolder) => {
            destFolder && filesService.getFiles({
                filesPath: destFolder,
                projObj: {
                    method: body.method,
                    fromWkid: body.iSrid,
                    toWkid: body.oSrid,
                },
                zipType: body.zipType
            }, ((success, outputDirPath,err) => {
                err && res.json({
                    code: 10200,    //业务失败
                    message: err,
                    data: {
                        
                    }
                });
                success && CommonUtil.zip(outputDirPath, (zipBufferData, zipFilePath, err) => {
                    // CommonUtil.getLocalIP();
                    const p = `http://${ip}:${port}/uploads/${body.oSrid || body.method || '4326'}.zip`;
                    res.json({
                        code: 200,
                        message: 'success',
                        data: {
                            data: zipBufferData,
                            zipFilePath: p
                        }
                    });
                })
            }))
        });
    } catch (error) {
        console.error(error);
    } finally {
        
    }

});

module.exports = router;